package com.century.sjt.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.Pay.TransactionDataActivity;
import com.century.sjt.activity.login.LoginActivity;
import com.century.sjt.adapter.PayTransactionRecordAdapter;
import com.century.sjt.entity.TransactionRecord;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 交易订单详情
 */
public class PayTransactionFragment extends BaseFragment {
    private List<TransactionRecord> mDataList;
    private ListView mListPtRecord;
    private PayTransactionRecordAdapter mAdapter;
    //    private Button loadMore;
    private Context mContext;

    private RequestQueue mQueue;
    private String pageSize = "10";
    private int iCurrPage = 1;
    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Handler mHandler;
    private Boolean isDataChangeOk = true;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sjt_pay_transaction_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        mQueue = Volley.newRequestQueue(getActivity());

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mAdapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk = true;
                        mDataList.clear();
                        iCurrPage = 1;
                        getRecords();
                        break;
                    case 3:
                        if (isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            iCurrPage++;
                            getRecords();
                        }
                        break;

                }
            }
        };
        initView();
        initEvents();


//        getStoreDetail(merchantId);


    }

    private void initEvents() {

        mAdapter = new PayTransactionRecordAdapter(mDataList, mContext);
        mListPtRecord.setAdapter(mAdapter);

        mListPtRecord.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler.sendMessage(msg);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });


        //更多记录
//        View bottomView=getLayoutInflater().inflate(R.layout.social_zone_listview_bottom, null);
//        loadMore=(Button)bottomView.findViewById(R.id.social_zone_listview_bottom_load);
//        loadMore.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                loadMore.setEnabled(false);
//                loadMore.setText("加载中");
//                getRecords();
//
//            }
//        });
//        mListPtRecord.addFooterView(bottomView);

        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mListPtRecord.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                intent.setClass(mContext,TransactionDataActivity.class);
                intent.putExtra("payType", "3");
                String txNo=mDataList.get(i).getTxNo();
                intent.putExtra("txNo",mDataList.get(i).getTxNo());
                startActivity(intent);
            }
        });
//        getRecords();
    }

    @Override
    public void onResume() {
//        getRecords();
        Message msg = new Message();
        msg.what = 2;
        mHandler.sendMessage(msg);
        super.onResume();
    }

    private void initView() {
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout) getView().findViewById(R.id.activity_list_refesh);
        mQueue = Volley.newRequestQueue(mContext);
        mDataList = new ArrayList<>();
        mListPtRecord = (ListView) getView().findViewById(R.id.list_pt_record);
    }

    //获取交易记录
    private void getRecords() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        isDataChangeOk = false;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.uTranscationRecordHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    isDataChangeOk = true;
                    TipUtil.log("交易记录", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject data = res.getJSONObject("data");
                    if (code.equals("407")){
                        TipUtil.showAppayRes(getActivity());
                    }
                    if (code.equals("200")) {//成功
                        JSONArray transRecordList = data.getJSONArray("transRecordList");
                        if (transRecordList.length()!= Constant.PAGESIZE) {
                            isDataChangeOk = false;
                            if (iCurrPage == 1 && data.length() == 0) {
//                                TipUtil.showToast(getResources().getString(R.string.error_pay_transaction_noting), mContext);
                            } else {
//                                TipUtil.showToast("无更多数据",mContext);
                            }
                        }
                            //接口2.0
                            for (int i=0;i<transRecordList.length();i++){
                                JSONObject dataObject = transRecordList.getJSONObject(i);
//                            Log.e("data",dataObject.toString());
                                TransactionRecord transactionRecord = new TransactionRecord();
                                transactionRecord.setTxNo(dataObject.getString("txNo"));
//                                transactionRecord.setRecieverName(dataObject.getString("recieverName"));
                                transactionRecord.setTxAmt(dataObject.getString("txAmt"));
                                transactionRecord.setTradeType(dataObject.getString("tradeType"));
                                transactionRecord.setTradeTypeName(dataObject.getString("tradeTypeName"));
                                transactionRecord.setTxDate(dataObject.getString("txDate"));
                                transactionRecord.setStatus(dataObject.getString("status"));
                                transactionRecord.setStatusName(dataObject.getString("statusName"));
                                transactionRecord.setAccountingType(dataObject.getString("accountingType"));
                                mDataList.add(transactionRecord);

                        }



                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                    TipUtil.closeProgressDialog();
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), mContext, 1);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
                isDataChangeOk = true;
                iCurrPage--;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                //1.0接口
//                map.put("paging.pageSize", Constant.PAGESIZE + "");
//                map.put("paging.currentPage", String.valueOf(iCurrPage));
                //2.0接口
                map.put("paging.currentPage",String.valueOf(iCurrPage));//当前页码
                map.put("paging.pageSize", Constant.PAGESIZE+" ");//查询条数
                map.put("transDate","时间");//交易日期
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    @Override
    public void onDestroy() {
        mQueue.cancelAll(this);
        super.onDestroy();
    }

}